import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/login.vue'
import Home from '../components/home.vue'
import Welcome from '../components/welcome.vue'
import Users from '../components/user/users.vue'

Vue.use(Router)

const router=new Router({
  routes: [
    // 重定向，定向到login界面
    {path:'/',redirect:'/login'},
    {path:'/login',component:Login},
    {
      path:'/home',
      //如果访问home就重定向到welcome
      redirect:'/welcome',
      component:Home,
      children:[
        {path:'/welcome',component:Welcome},
        {path:'/users',component:Users}
      ]
    },
  ]
})

//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //to 将要访问的路径
  //from 代表从哪个路径转跳而来
  //next是一个函数，表示放行
  // next()   放行   next('/login')   强制跳转
  //如果用户访问的登录页，直接放行
  if(to.path === '/login') return next()
  //从sessionStorage中获取到 保存到token值
  const tokenStr=window.sessionStorage.getItem('token')
  //没有token，强制跳转到登录页
  if(!tokenStr) return next('./login')
  next()
})

export default router